﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Security.Cryptography;

public partial class Admin_Login : System.Web.UI.Page
{
    AdminBUS adBUS = new AdminBUS();
    DataTable tbAdmin = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            txtUser.Focus();
            if (Request.Cookies["myCookie"] != null)
            {
                HttpCookie cookie = Request.Cookies.Get("myCookie");
                txtUser.Text = cookie.Values["username"];
                txtPass.Attributes.Add("value", cookie.Values["password"]);
                cbxRemember.Checked = true;
            }
        }
    }
    public string Md5AddSecret(string strChange)
    {
        //Change the syllable into UTF8 code
        byte[] pass = Encoding.UTF8.GetBytes(strChange);
        MD5 md5 = new MD5CryptoServiceProvider();
        string strPassword = Encoding.UTF8.GetString(md5.ComputeHash(pass));
        return strPassword;
    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        bool IsRemember = cbxRemember.Checked;
        string passMD5 = Md5AddSecret(txtPass.Text);
        HttpCookie myCookie = new HttpCookie("myCookie");
        if (txtUser.Text.Equals("") || txtPass.Text.Equals(""))
        {
            lblError.Text = "You must enter enough information";
        }
        else
        {
            tbAdmin = adBUS.isValidLogin(txtUser.Text, passMD5);
            if (tbAdmin.Rows.Count > 0)
            {
                Session["MemID"] = tbAdmin.Rows[0]["ID"];
                Session["MemUser"] = tbAdmin.Rows[0]["UserName"];

                if (IsRemember)
                {
                    myCookie.Values.Add("username", txtUser.Text);
                    myCookie.Values.Add("password", txtPass.Text);
                    myCookie.Expires = DateTime.Now.AddDays(15);
                }
                else
                {
                    myCookie.Values.Add("username", string.Empty);
                    myCookie.Values.Add("password", string.Empty);
                    myCookie.Expires = DateTime.Now.AddDays(-1d);
                }
                Response.Cookies.Add(myCookie);
                Response.Redirect("Bill.aspx");
            }
            else
            {
                lblError.Text = "Wrong Password";
                txtPass.Text = "";
            }
        }
    }
}